package com.doit.mr.day07.shew;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.Iterator;

/**
 * @DATE 2021/12/9/11:57
 * @Author MDK
 * @Version 2021.2.2
 **/
public class SkewDemo03 {
    static class SkewDemo03Mapper extends Mapper<LongWritable, Text, Text, IntWritable>{
        Text k = new Text();
        IntWritable v = new IntWritable();
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                String line = value.toString();
                String cnt = line.split("\\s")[1];
                String word = line.split("-")[0];
                k.set(word);
                v.set(Integer.parseInt(cnt));
                context.write(k,v);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class SkewDemo03Reducer extends Reducer<Text, IntWritable, Text, IntWritable>{

        IntWritable v = new IntWritable();
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int cnt = 0;
            for (IntWritable value : values) {
                cnt += value.get();
            }
            v.set(cnt);
            context.write(key, v);
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "SkewDemo03");
        job.setMapperClass(SkewDemo03Mapper.class);
        job.setReducerClass(SkewDemo03Reducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path("D:\\mrdata\\skew\\output1"));
        FileOutputFormat.setOutputPath(job, new Path("D:\\mrdata\\skew\\opt1"));
        job.waitForCompletion(true);
    }
}
